package wh.coach._compare;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author hangwen
 * @date 2023/7/3
 */
public class Main {
    public static void main(String[] args) {
        //类型一致，且实现了comparable,直接使用自然的升级|降序
        List<Integer> numbers = Arrays.asList(4, 3, 1, 5, 2, 6);

        System.out.println("排序前：" + numbers);
        Collections.sort(numbers);
        System.out.println("升序：" + numbers);
        Collections.sort(numbers, Comparator.reverseOrder());
        System.out.println("降序：" + numbers);

        //为什么Collections.sort可以对数字排序？
        //因为Integer实现了Comparable接口

        //以下集合是否可以排序？
        List<Number> list = Arrays.asList(4, 3, 1, 5, 2, 6L);
        //类型不一致，只能传入比较器
        Collections.sort(list, (num1, num2) -> Long.compare(num1.longValue(), num2.longValue()));
        System.out.println("升序  List<Number：" + list);

        final long now = 0;

        //自定义排序
        List<Point> points = new ArrayList<>(Arrays.asList(
                new Point(now + 400, 5.0d),
                new Point(now + 300, 1.0d),
                new Point(now + 400, 6.0d),
                new Point(now + 500, 3.0d),
                new Point(now + 200, 2.0d),
                new Point(now + 600, 4.0d)
        ));

        //方法一 Point可以被比较,
        //如果p存在null,原生集合(Comparable)排序一定会报错
        Collections.sort(points);
        System.out.println("升序  points：" + points);

        //方法二 传入比较器

        //按时间升序
        Collections.sort(points, (p1, p2) -> Long.compare(p1.getTs(), p2.getTs()));
        Collections.sort(points, Comparator.comparingLong(p -> p.getTs()));
        //如果p存在null
        points.add(null);
        Collections.sort(points, (p1, p2) -> {
            if (p1 == null && p2 == null) {
                return 0;
            }

            if (p1 == null) {
                return -1;
            }

            if (p2 == null) {
                return 1;
            }

            return Long.compare(p1.getTs(), p2.getTs());
        });

        Collections.sort(points, Comparator.nullsFirst((p1, p2) -> Long.compare(p1.getTs(), p2.getTs())));
        Collections.sort(points, Comparator.nullsFirst(Comparator.comparingLong(Point::getTs)));

        System.out.println("升序 含有null的 points：" + points);

//        Collections.sort(points, (p1, p2) -> Long.compare(p1.getTs(), p2.getTs()));

        //作业：稳定排序
        //{name:"a",point:100},{name:"b",point:100},{name:"c",point:90} 升序后
        //{name:"c",point:90}，{name:"a",point:100},{name:"b",point:100} //稳定
        //{name:"c",point:90}，{name:"b",point:100},{name:"a",point:100} //不稳定
    }
}
